package com.dianrui.operation.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.SecretProtocolAdapter;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;
import com.tbit.tbitblesdk.Bike.TbitBle;
import com.tbit.tbitblesdk.Bike.model.BikeState;
import com.tbit.tbitblesdk.Bike.services.command.callback.StateCallback;
import com.tbit.tbitblesdk.protocol.callback.ResultCallback;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 盒子上下线
 */
public class DeviceDefenseActivity extends BaseActivity {
    private String mTitles;
    private BluetoothAdapter mBlueadapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.car_name_input)
    EditText inputImel;


    @Override
    public int getContentViewId() {
        return R.layout.device_defense;
    }

    @Override
    public void initView() {
        TbitBle.initialize(DeviceDefenseActivity.this, new SecretProtocolAdapter());
        mBlueadapter = BluetoothAdapter.getDefaultAdapter();
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("title");
                title.setText(mTitles);
            }
        }
    }

    @Override
    public void initData() {
    }

    @OnClick({R.id.back, R.id.withdraw_defense, R.id.setup_defense, R.id.scans})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            //撤防
            case R.id.withdraw_defense:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                    return;
                }
                withdrawDefense();
                break;
            //设防
            case R.id.setup_defense:
                if (StringUtils.isEmpty(inputImel.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                    return;
                }
                startDefense();
                break;

            case R.id.scans:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(DeviceDefenseActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent = new Intent(DeviceDefenseActivity.this, OpeationCaptureActivity.class);
                        intent.putExtra("camflag", "1");
                        startActivityForResult(intent, 102);
                    } else {
                        ActivityCompat.requestPermissions(DeviceDefenseActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent intent = new Intent(DeviceDefenseActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag", "1");
                    startActivityForResult(intent, 102);
                }
                break;

            default:
                break;


        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 102) {
            String imel = data.getStringExtra("IMEI");
            if (!StringUtils.isEmpty(imel)) {
                inputImel.setText(imel);
            }

        }
    }

    //设备上线
    private void withdrawDefense() {
        showLoadingDialog("撤防中...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", inputImel.getText().toString());
        jsonObject.addProperty("sw", "0");//设防，1设防，0撤防
        jsonObject.addProperty("type", "3");//3是设防撤防
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {

                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                AlertDialog.Builder builder = new AlertDialog.Builder(DeviceDefenseActivity.this, R.style.activity_dialog);
                                View view = LayoutInflater.from(DeviceDefenseActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                final AlertDialog conituredialog = builder.create();
                                conituredialog.setView(view);
                                conituredialog.show();
                                final TextView contents = view.findViewById(R.id.content);
                                final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                final Button cancel = view.findViewById(R.id.cancel);
                                contents.setText(jsonObject.optString("message"));
                                cancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        conituredialog.dismiss();
                                    }
                                });
                                endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        conituredialog.dismiss();
                                        if (!mBlueadapter.isEnabled()) {
                                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                            ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                        } else {
                                            connectBlueTeeth(inputImel.getText().toString(), jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"), "1");
                                        }

                                    }
                                });
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }


    private void startDefense() {//设防
        showLoadingDialog("设防中...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", inputImel.getText().toString());
        jsonObject.addProperty("sw", "1");//设防，1设防，0撤防
        jsonObject.addProperty("type", "3");//3是设防撤防
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {

                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                AlertDialog.Builder builder = new AlertDialog.Builder(DeviceDefenseActivity.this, R.style.activity_dialog);
                                View view = LayoutInflater.from(DeviceDefenseActivity.this).inflate(R.layout.blue_endcar_dialog, null);
                                final AlertDialog conituredialog = builder.create();
                                conituredialog.setView(view);
                                conituredialog.show();
                                final TextView contents = view.findViewById(R.id.content);
                                final Button endCarstartCars = view.findViewById(R.id.start_cars);
                                final Button cancel = view.findViewById(R.id.cancel);
                                contents.setText(jsonObject.optString("message"));
                                cancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        conituredialog.dismiss();
                                    }
                                });
                                endCarstartCars.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        conituredialog.dismiss();
                                        if (!mBlueadapter.isEnabled()) {
                                            startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                                            ToastUtil.showToast(getString(R.string.please_open_blueteeth));
                                        } else {
                                            connectBlueTeeth(inputImel.getText().toString(), jsonObject.optJSONObject("data").optString("device"), jsonObject.optJSONObject("data").optString("token"), "2");
                                        }

                                    }
                                });
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    private void connectBlueTeeth(final String number, String devices, String token, final String blueCommandType) {
        showLoadingDialog("正在连接蓝牙中");
        TbitBle.connect(devices, token, new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                // 连接回应
                Log.e("连接成功后回应状态码-->", resultCode + "");
                if (resultCode == 0) {
                    if (blueCommandType.equals("1")) {
                        unlockDevice(number);
                    } else if (blueCommandType.equals("2")) {
                        lockDevice(number);
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtil.showToast( " 蓝牙连接失败，请重新再试");
                }
            }
        }, new StateCallback() {
            @Override
            public void onStateUpdated(BikeState bikeState) {
                dismissLoadingDialog();

            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(DeviceDefenseActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag", "1");
                    startActivityForResult(intent, 102);
                }
                break;

            default:
                break;

        }

    }


    // 解锁
    private void unlockDevice(final String number) {
        TbitBle.unlock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                if (resultCode == 0) {
                    blueTeethStartDevice(number);
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请稍候再试");
                }
            }
        });
    }

    // 上锁
    private void lockDevice(final String number) {
        TbitBle.lock(new ResultCallback() {
            @Override
            public void onResult(int resultCode) {
                dismissLoadingDialog();
                if (resultCode == 0) {
                    blueTeethCloseDevice(number);
                }else {
                    ToastUtil.showToast("蓝牙操作失败,请稍候再试");
                }
            }
        });


    }

    //蓝牙开启设备后回传给后台
    private void blueTeethStartDevice(String number) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", "1");
        jsonObject.addProperty("type", "2");
        jsonObject.addProperty("is_bluetooth", "1");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    private void blueTeethCloseDevice(String number) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("number", number);
        jsonObject.addProperty("sw", "0");
        jsonObject.addProperty("type", "2");
        jsonObject.addProperty("is_bluetooth", "1");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.QUERYVEHCLES, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        dismissLoadingDialog();
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TbitBle.disConnect();
        TbitBle.destroy();
    }
}
